#!/usr/bin/env python3
"""
Metaso服务使用示例
演示如何使用Metaso服务进行数据查询和分析
"""

import requests
import time
import json
from datetime import datetime

# 配置
BASE_URL = "http://localhost:5000/api/v1/metaso"

def example_basic_query():
    """基本查询示例"""
    print("=" * 60)
    print("基本查询示例")
    print("=" * 60)
    
    # 1. 启动查询任务
    query_text = "中国医药市场规模2025年和2030年的预测数据是多少？对应的美元价值和复合年增长率是多少？"
    
    print(f"查询问题: {query_text}")
    print("正在启动查询任务...")
    
    try:
        response = requests.post(f"{BASE_URL}/query", json={
            "query_text": query_text,
            "scope": "webpage",
            "size": 20
        })
        
        if response.status_code == 200:
            result = response.json()
            task_id = result.get('task_id')
            print(f"✓ 查询任务启动成功，任务ID: {task_id}")
            
            # 2. 等待任务完成
            print("等待任务完成...")
            max_wait_time = 120  # 最大等待时间2分钟
            start_time = time.time()
            
            while time.time() - start_time < max_wait_time:
                status_response = requests.get(f"{BASE_URL}/task/{task_id}/status")
                if status_response.status_code == 200:
                    status_data = status_response.json()
                    task_status = status_data.get('data', {}).get('status')
                    print(f"任务状态: {task_status}")
                    
                    if task_status == 'completed':
                        print("✓ 任务完成！")
                        break
                    elif task_status == 'failed':
                        print("✗ 任务失败")
                        return
                    elif task_status == 'cancelled':
                        print("任务已取消")
                        return
                
                time.sleep(10)  # 等待10秒后再次检查
            
            # 3. 获取查询结果
            if task_status == 'completed':
                print("\n获取查询结果...")
                result_response = requests.get(f"{BASE_URL}/query/{task_id}")
                if result_response.status_code == 200:
                    result_data = result_response.json()
                    data = result_data.get('data', {})
                    
                    print(f"\n查询结果:")
                    print(f"查询时间: {data.get('query_time', '')}")
                    print(f"总结果数: {data.get('total_results', 0)}")
                    print(f"使用积分: {data.get('credits_used', 0)}")
                    print(f"置信度: {data.get('confidence_score', 0):.2f}")
                    
                    print(f"\nGLM4.5分析结果:")
                    analysis_result = data.get('analysis_result', '')
                    print(analysis_result[:500] + "..." if len(analysis_result) > 500 else analysis_result)
                    
                    print(f"\n网页数据 ({len(data.get('webpages', []))} 条):")
                    for i, webpage in enumerate(data.get('webpages', [])[:3], 1):  # 只显示前3条
                        print(f"{i}. {webpage.get('title', '')}")
                        print(f"   链接: {webpage.get('link', '')}")
                        print(f"   摘要: {webpage.get('snippet', '')[:100]}...")
                        print()
                    
                else:
                    print(f"获取查询结果失败: {result_response.status_code}")
            else:
                print("任务未在预期时间内完成")
                
        else:
            print(f"启动查询任务失败: {response.status_code}")
            print(f"错误信息: {response.text}")
            
    except Exception as e:
        print(f"查询过程中发生异常: {str(e)}")

def example_batch_queries():
    """批量查询示例"""
    print("\n" + "=" * 60)
    print("批量查询示例")
    print("=" * 60)
    
    queries = [
        "中国医药市场增长的主要驱动因素有哪些？",
        "医保扩容政策对医药市场的影响",
        "创新药审批加速政策最新进展",
        "生物药及创新药研发投入增加情况"
    ]
    
    task_ids = []
    
    # 启动多个查询任务
    for i, query in enumerate(queries, 1):
        print(f"\n启动查询 {i}: {query[:50]}...")
        
        try:
            response = requests.post(f"{BASE_URL}/query", json={
                "query_text": query,
                "scope": "webpage",
                "size": 15
            })
            
            if response.status_code == 200:
                result = response.json()
                task_id = result.get('task_id')
                task_ids.append(task_id)
                print(f"✓ 查询 {i} 启动成功，任务ID: {task_id}")
            else:
                print(f"✗ 查询 {i} 启动失败")
                
        except Exception as e:
            print(f"✗ 查询 {i} 异常: {str(e)}")
    
    # 等待所有任务完成
    if task_ids:
        print(f"\n等待 {len(task_ids)} 个查询任务完成...")
        
        completed_tasks = []
        start_time = time.time()
        max_wait_time = 300  # 最大等待时间5分钟
        
        while len(completed_tasks) < len(task_ids) and time.time() - start_time < max_wait_time:
            for task_id in task_ids:
                if task_id not in completed_tasks:
                    try:
                        status_response = requests.get(f"{BASE_URL}/task/{task_id}/status")
                        if status_response.status_code == 200:
                            status_data = status_response.json()
                            task_status = status_data.get('data', {}).get('status')
                            
                            if task_status in ['completed', 'failed']:
                                completed_tasks.append(task_id)
                                print(f"任务 {task_id} {task_status}")
                    
                    except Exception as e:
                        print(f"检查任务 {task_id} 状态失败: {str(e)}")
            
            if len(completed_tasks) < len(task_ids):
                time.sleep(15)  # 等待15秒后再次检查
        
        print(f"完成的任务数: {len(completed_tasks)}/{len(task_ids)}")

def example_search_history():
    """搜索历史查询示例"""
    print("\n" + "=" * 60)
    print("搜索历史查询示例")
    print("=" * 60)
    
    # 搜索包含特定关键词的查询
    keywords = ["医药", "市场规模", "预测"]
    
    try:
        response = requests.post(f"{BASE_URL}/search", json={
            "keywords": keywords,
            "limit": 10
        })
        
        if response.status_code == 200:
            result = response.json()
            search_results = result.get('data', [])
            
            print(f"关键词: {', '.join(keywords)}")
            print(f"找到 {len(search_results)} 条相关查询:")
            
            for i, query in enumerate(search_results, 1):
                print(f"\n{i}. 查询时间: {query.get('query_time', '')}")
                print(f"   查询内容: {query.get('query_text', '')[:100]}...")
                print(f"   状态: {query.get('status', '')}")
                print(f"   结果数: {query.get('total_results', 0)}")
                
        else:
            print(f"搜索失败: {response.status_code}")
            
    except Exception as e:
        print(f"搜索过程中发生异常: {str(e)}")

def example_get_statistics():
    """获取统计信息示例"""
    print("\n" + "=" * 60)
    print("获取统计信息示例")
    print("=" * 60)
    
    try:
        response = requests.get(f"{BASE_URL}/statistics")
        
        if response.status_code == 200:
            result = response.json()
            stats = result.get('data', {})
            
            print("查询统计信息:")
            print(f"总查询数: {stats.get('total_queries', 0)}")
            print(f"完成查询数: {stats.get('completed_queries', 0)}")
            print(f"失败查询数: {stats.get('failed_queries', 0)}")
            print(f"待处理查询数: {stats.get('pending_queries', 0)}")
            print(f"成功率: {stats.get('success_rate', 0):.1f}%")
            
            print(f"\n最近7天查询统计:")
            for daily_stat in stats.get('daily_stats', []):
                print(f"  {daily_stat.get('date', '')}: {daily_stat.get('count', 0)} 次查询")
                
        else:
            print(f"获取统计信息失败: {response.status_code}")
            
    except Exception as e:
        print(f"获取统计信息过程中发生异常: {str(e)}")

def main():
    """主函数"""
    print("Metaso服务使用示例")
    print("请确保Metaso服务正在运行 (python src/main.py)")
    print()
    
    try:
        # 测试服务是否可用
        response = requests.get(f"{BASE_URL}/health")
        if response.status_code != 200:
            print("❌ Metaso服务不可用，请先启动服务")
            return
        
        print("✅ Metaso服务可用，开始示例演示")
        
        # 运行各种示例
        example_basic_query()
        example_batch_queries()
        example_search_history()
        example_get_statistics()
        
        print("\n" + "=" * 60)
        print("示例演示完成！")
        print("=" * 60)
        
    except requests.exceptions.ConnectionError:
        print("❌ 无法连接到Metaso服务，请确保服务正在运行")
        print("启动命令: python src/main.py")
    except Exception as e:
        print(f"❌ 运行示例时发生异常: {str(e)}")

if __name__ == "__main__":
    main()
